<template>
  <view class="container">
    
    <view class="boxPanel p-t-26 p-b-26 p-l-30 p-r-30 flex-between radius-20 m-l-24 m-r-24 m-b-24">
      <view class="name">收货人</view>
      <view class="row-right" style="flex: 1;">
         <input type="text" placeholder="请输入" v-model="formData.name"  class="inputs" style="text-align: right;">
      </view>
    </view>
    
    <view class="boxPanel p-t-26 p-b-26 p-l-30 p-r-30 flex-between radius-20 m-l-24 m-r-24 m-b-24">
      <view class="name">手机号</view>
      <view class="row-right" style="flex: 1;">
         <input type="number" placeholder="请输入" v-model="formData.mobile"  class="inputs" style="text-align: right;" maxlength="11">
      </view>
    </view>
    
    <view class="boxPanel p-t-26 p-b-26 p-l-30 p-r-30 flex-between radius-20 m-l-24 m-r-24 m-b-24">
      <view class="name">选择地址</view>
      <view class="row-right flex-y-center" style="flex: 1;" @click="selectAddress">
        <!-- <pick-regions :default-regions="defaultRegions" @getRegions="handleGetRegions" >
        	<text :class="!formData.full_address?'c-87':''">
        		{{ formData.full_address ? formData.full_address : '请选择地址' }}
        	</text>
        </pick-regions> -->
		<view >
			<text :class="!formData.full_address?'c-87':''">
        		{{ formData.full_address ? formData.full_address : '请选择地址' }}
        	</text>
		</view>
		<view style="margin-top: 10rpx;">
			<i class="iconfont">&#xe695;</i>
		</view>
      </view>
    </view>
    
    <view class="boxPanel p-t-26 p-b-26 p-l-30 p-r-30 flex-between radius-20 m-l-24 m-r-24 m-b-24">
      <textarea cols="30" rows="10" placeholder="请输入" v-model="formData.address"></textarea>
    </view>
    
    <view class="boxPanel p-t-26 p-b-26 p-l-30 p-r-30 flex-between radius-20 m-l-24 m-r-24 m-b-24">
      <view class="name">设为默认地址</view>
      <u-switch v-model="formData.is_default" activeColor="#1AC67E" size="20" @change="change"></u-switch>
    </view>
  
	<view class="footer fixfooter" :class="{ 'bottom-safe-area': isIphoneX }">
		<view class="submit" @click="saveAddress()">保存</view>
	</view>
    
  </view>
</template>

<script>
  import pickRegions from '@/components/pick-regions/pick-regions.vue';
  import validate from 'common/js/validate.js';
  export default {
    components: {
    	pickRegions
    },
    data() {
      return {
        isIphoneX: false, //判断手机是否是iphoneX以上
        formData: {
          name: '',
          mobile: '',
          province_id: '',
          city_id: '',
          district_id: '',
          address: '',
          is_default: true,
          address_id: 0,
          full_address: '',
		  latitude: 0,
		  longitude: 0

        },
        addressValue: '',
        flag: false, //防重复标识
        back: '/pages/address/address', // 返回页
        redirect: 'redirectTo', // 跳转方式
        //地区
        defaultRegions: [],
      }
    },
    onLoad(option) {
      this.isIphoneX = this.$util.uniappIsIPhoneX()
      
			if (option.back) this.back = option.back;
			if (option.redirect) this.redirect = option.redirect;
      if (option.address_id) {
      	this.formData.address_id = option.address_id;
      	this.getAddressDetail();
      }
    },
    onShow() {
      if (this.formData.address_id) {
      	uni.setNavigationBarTitle({
      		title: '编辑地址'
      	});
      } else {
      	uni.setNavigationBarTitle({
      		title: '新增地址'
      	});
      }
    },
    methods: {
      change(e) {
        this.formData.is_default = e;
      },
      getAddressDetail() {
      	this.$api.sendRequest({
      		url: '/api/memberaddress/info',
      		data: {
      			id: this.formData.address_id
      		},
      		success: res => {
      			let data = res.data;
      			if (data != null) {
      				this.formData.name = data.name;
      				this.formData.mobile = data.mobile;
      				this.formData.address = data.address;
      				this.formData.full_address = data.full_address;
      				this.formData.is_default = data.is_default==1?true:false;
					this.formData.latitude = data.latitude;
					this.formData.longitude = data.longitude;
      				this.addressValue = '';
      				this.addressValue += res.data.province_id != undefined ? res.data.province_id : '';
      				this.addressValue += res.data.city_id != undefined ? '-' + res.data.city_id : '';
      				this.addressValue += res.data.district_id != undefined ? '-' + res.data.district_id : '';
      				this.defaultRegions = [data.province_id, data.city_id, data.district_id];
      			}
      		}
      	});
      },
      // 获取选择的地区
      handleGetRegions(regions) {
        console.log(regions)
      	this.formData.full_address = '';
      	this.formData.full_address += regions[0] != undefined ? regions[0].label : '';
      	this.formData.full_address += regions[1] != undefined ? '-' + regions[1].label : '';
      	this.formData.full_address += regions[2] != undefined ? '-' + regions[2].label : '';
      	this.addressValue = '';
      	this.addressValue += regions[0] != undefined ? regions[0].value : '';
      	this.addressValue += regions[1] != undefined ? '-' + regions[1].value : '';
      	this.addressValue += regions[2] != undefined ? '-' + regions[2].value : '';
      },
	  selectAddress() {
			// #ifdef MP
			uni.chooseLocation({
				success: res => {
					console.log(res)
					this.formData.latitude = res.latitude;
					this.formData.longitude = res.longitude;
					this.formData.address = res.name;
					this.getAddress(res.longitude + ',' + res.latitude);
				},
				fail(res) {
					uni.getSetting({
						success: function(res) {
							var statu = res.authSetting;
							if (!statu['scope.userLocation']) {
								uni.showModal({
									title: '是否授权当前位置',
									content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
									success(tip) {
										if (tip.confirm) {
											uni.openSetting({
												success: function(data) {
													if (data.authSetting['scope.userLocation'] === true) {
														this.$util.showToast({
															title: '授权成功'
														});
														//授权成功之后，再调用chooseLocation选择地方
														setTimeout(function() {
															uni.chooseLocation({
																success: data => {
																	this.formData.latitude = res.latitude;
																	this.formData.longitude = res.longitude;
																	this.formData.address = res.name;
																	this.getAddress(res.longitude + ',' + res.latitude);
																}
															});
														}, 1000);
													}
												}
											});
										} else {
											this.$util.showToast({
												title: '授权失败'
											});
										}
									}
								});
							}
						}
					});
				}
			});
			// #endif
			// #ifdef H5
			var urlencode = this.formData;
			uni.setStorageSync('addressInfo', urlencode);
			let backurl = Config.h5Domain + '/pages/addAddress/addAddress?type=' + this.localType;
			if (this.formData.id) backurl += '&id=' + this.formData.id;
			if (this.back) backurl += '&back=' + this.back;

			window.location.href = 'https://apis.map.qq.com/tools/locpicker?search=1&type=0&backurl=' + encodeURIComponent(
				backurl) + '&key=' + Config.mpKey + '&referer=myapp';
			// #endif
		},
		//获取详细地址
		getAddress(value) {
			this.$api.sendRequest({
				url: '/api/memberaddress/tranAddressInfo',
				data: {
					latlng: value
				},
				success: res => {
					if (res.code == 0) {
						this.formData.full_address = '';
						this.formData.full_address += res.data.province != undefined ? res.data.province : '';
						this.formData.full_address += res.data.city != undefined ? '-' + res.data.city : '';
						this.formData.full_address += res.data.district != undefined ? '-' + res.data.district : '';
						this.addressValue = '';
						this.addressValue += res.data.province_id != undefined ? res.data.province_id : '';
						this.addressValue += res.data.city_id != undefined ? '-' + res.data.city_id : '';
						this.addressValue += res.data.district_id != undefined ? '-' + res.data.district_id : '';
					} else {
						this.showToast({
							title: '数据有误'
						});
					}
				}
			});
		},
      vertify() {
      	this.formData.name = this.formData.name.trim();
      	this.formData.mobile = this.formData.mobile.trim();
      	this.formData.address = this.formData.address.trim();
      	var rule = [
      		{
      			name: 'name',
      			checkType: 'required',
      			errorMsg: '请输入姓名'
      		},
      		{
      			name: 'mobile',
      			checkType: 'required',
      			errorMsg: '请输入手机号'
      		},
      		{
      			name: 'full_address',
      			checkType: 'required',
      			errorMsg: '请选择地址'
      		},
      		{
      			name: 'address',
      			checkType: 'required',
      			errorMsg: '详细地址不能为空'
      		}
      	];
      	var checkRes = validate.check(this.formData, rule);
      	if (checkRes) {
      		return true;
      	} else {
      		this.$util.showToast({
      			title: validate.error
      		});
      		this.flag = false;
      		return false;
      	}
      },
      saveAddress() {
      	if (this.flag) return;
      	this.flag = true;
      	if (this.vertify()) {
      		let addressValueArr = this.addressValue.split('-'),
      			data = {};
      
      		data = {
      			name: this.formData.name,
      			mobile: this.formData.mobile,
      			province_id: addressValueArr[0],
      			city_id: addressValueArr[1],
      			district_id: addressValueArr[2],
				full_address: this.formData.full_address,
      			address: this.formData.address,
      			is_default: this.formData.is_default?1:0,
				latitude: this.formData.latitude,
				longitude: this.formData.longitude,
				type: 2
      		};

			let url = "/api/memberaddress/add";
      
      		
      		if (this.formData.address_id) {
      			data.id = this.formData.address_id;
				url = "/api/memberaddress/edit";
      		}
      		this.$api.sendRequest({
      			url: url,
      			data: data,
      			success: res => {
      				this.flag = false;
      				if (res.code == 0) {
      					if (this.back != '') {
      						let jump = true;
      						let arr = getCurrentPages().reverse();
      						for (let i = 0; i < arr.length; i++) {
      							if (this.back.indexOf(arr[i].route) != -1) {
      								jump = false;
      								uni.navigateBack({
      									delta: i
      								});
      								break;
      							}
      						}
      						if (jump) {
      							this.$util.redirectTo(this.back, {}, 'redirectTo');
      						}
      					} else {
      						this.$util.showToast({
      							title: res.message
      						});
      						uni.navigateBack({
      							delta: 1
      						});
      					}
      				}else {
								this.$util.showToast({
									title: res.message
								});
							}
      			},
      			fail: res => {
      				this.flag = false;
      			}
      		});
      	}
      },
    }
  }
</script>

<style lang="scss" scoped>
.row-right {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.iconfont {
	  color: #878DA1;
	  font-size: 40rpx;
  }
</style>
